const DB = require('../core/DB')
const {
    Op
} = require('sequelize')


DB.message.belongsTo(DB.user)
DB.message.hasMany(DB.reply)

DB.comment.belongsTo(DB.user)
DB.comment.belongsTo(DB.article)
DB.comment.hasMany(DB.reply)

DB.reply.belongsTo(DB.comment)
DB.reply.belongsTo(DB.message)



class MsgController {
    /* ------------------------------------- ok 加载文章评论 -----------------------------------------*/
    async loadArticleComment(ctx) {
        let {
            articleId
        } = ctx.query

        const comments = await DB.comment.findAll({
            where: {
                articleId,
                status: 1
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'email', 'name']
            }]
        })

        // 加载回复
        for (let commentItem of comments) {
            const replies = await DB.reply.findAll({
                where: {
                    commentId: commentItem.get('id'),
                    status: 1 // 审核通过
                }
            })
            for (let replyItem of replies) {
                let userId = replyItem.get('userId')
                let replyUserId = replyItem.get('replyUserId')
                // 回复用户
                let user = await DB.user.findByPk(userId, {
                    attributes: ['id', 'email', 'name']
                })
                // 被回复用户
                let replyUser = await DB.user.findByPk(replyUserId, {
                    attributes: ['id', 'email', 'name']
                })
                replyItem.dataValues.user = user
                replyItem.dataValues.replyUser = replyUser
            }
            commentItem.dataValues.replies = replies
        }

        global.Response.success(ctx, undefined, comments)
    }


    /* ------------------------------------------- ok 新建评论 ----------------------------------------------*/
    async createComment(ctx) {
        let {
            // anonymity = false, // 匿名
            userId,
            content,
            articleId
        } = ctx.request.body

        // if (anonymity){ // 是否匿名

        // }

        const comment = await DB.comment.create({
            userId,
            content,
            articleId,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        if (comment) {
            global.Response.success(ctx)
        } else {
            global.Response.fail(ctx)
        }
    }

    /* ------------------------------------------------ok  删除评论 --------------------------------------------------------*/
    async deleteComment(ctx) {
        const {
            id
        } = ctx.query
        await DB.comment.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        // 删除评论下的所有回复
        await DB.reply.destroy({ // return 1 or 0
            where: {
                commentId: id
            }
        })

        global.Response.success(ctx, '删除成功')

    }

    /* ------------------------------------------------ ok 新建留言 --------------------------------------------------------*/
    async createMessage(ctx) {
        let {
            userId,
            content,
            status = 1, // 显示or隐藏
        } = ctx.request.body

        const message = await DB.message.create({
            userId,
            content,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        global.Response.success(ctx)
    }

    /* ------------------------------------------------ ok 留言列表 --------------------------------------------------------*/
    async listMessage(ctx) {
        // 参数
        let {
            page = 1, size = 10, key = '', admin = 0
        } = ctx.query

        page = Number(page)
        size = Number(size)

        const {
            count,
            rows
        } = await DB.message.findAndCountAll({
            where: {
                status: 1 // 审核通过
            },
            offset: (page - 1) * size,
            limit: size,
            include: [{
                model: DB.user,
                attributes: ['id', 'email', 'name']
            }]
        })

        for (let message of rows) {
            // 获取id 前往reply查找
            let messageId = message.get('id')
            const { count: replyCount, rows: replies } = await DB.reply.findAndCountAll({
                where: {
                    messageId,
                    status: 1 // 审核通过
                }
            })

            message.dataValues.replies = replies || []

            if (replies.length > 0) {
                for (let reply of replies) {
                    let userId = reply.get('userId')
                    let replyUserId = reply.get('replyUserId')
                    // 回复用户
                    let user = await DB.user.findByPk(userId, {
                        attributes: {
                            exclude: ['password', 'createdAt', 'updatedAt']
                        }
                    })
                    // 被回复用户
                    let replyUser = await DB.user.findByPk(replyUserId, {
                        attributes: {
                            exclude: ['password', 'createdAt', 'updatedAt']
                        }
                    })
                    reply.dataValues.user = user
                    reply.dataValues.replyUser = replyUser
                }
            }
            message.dataValues.replyCount = replies.length
        }


        const data = {
            rows,
            meta: {
                key,
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)

    }

    /* ------------------------------------------------ok 删除留言 --------------------------------------------------------*/
    async deleteMessage(ctx) {
        const {
            id
        } = ctx.query
        let res = await DB.message.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        // 删除评论下的所有回复
        res = await DB.reply.destroy({ // return 1 or 0
            where: {
                messageId: id
            }
        })

        global.Response.success(ctx, '删除成功')

    }

    /* ------------------------------------------------ ok 回复列表 --------------------------------------------------------*/
    async listReply(ctx) {
        // 参数
        const {
            page = 1, size = 10, key = ''
        } = ctx.query

        const {
            count,
            rows
        } = await DB.reply.findAndCountAll({
            // where: {
            //     title: {
            //         [Op.substring]: key
            //     }
            // },
            offset: page - 1,
            limit: size,
        })


        for (let i in rows) {
            let item = rows[i]
            let userId = item.get('userId')
            let user = await DB.user.findByPk(userId, {
                attributes: {
                    exclude: ['password']
                }
            })
            let replyUserId = item.get('replyUserId')
            let replyUser = await DB.user.findByPk(replyUserId, {
                attributes: {
                    exclude: ['password']
                }
            })

            item.dataValues.name = user.name
            item.dataValues.replyName = replyUser.name
            item.dataValues.email = user.email
        }

        const data = {
            rows,
            meta: {
                key,
                page: page, // 当前页数
                size, // 每页条目
                count: count, // 条目总数
                total: Math.ceil(count / size), // 总页数
            }
        }

        global.Response.success(ctx, undefined, data)
    }

    /* ------------------------------------------------ ok 新建回复 --------------------------------------------------------*/
    async createReply(ctx) {
        const {
            userId,
            replyUserId,
            commentId,
            messageId,
            content,
            status = 1
        } = ctx.request.body

        const reply = await DB.reply.create({
            userId,
            replyUserId,
            commentId,
            messageId,
            content,
            status,
            read: 0, // 未读
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        })

        if (reply) {
            global.Response.success(ctx)
        } else {
            global.Response.fail(ctx)
        }
    }

    /* ------------------------------------------------ok 加载回复 个人收到的回复 --------------------------------------------------------*/
    async loadReply(ctx) {
        const {
            replyUserId,
        } = ctx.query

        const replys = await DB.reply.findAll({
            where: {
                replyUserId
            },
        })
        for (let i in replys) {
            let item = replys[i]
            let userId = item.get('userId')
            let user = await DB.user.findByPk(userId, {
                attributes: ['name', 'admin']
            })
            let comment = await DB.comment.findByPk(item.get('commentId'))
            if (comment) {
                item.dataValues.articleId = comment.get('articleId') // 文章Id
            }
            item.dataValues.userName = user.get('name')
            item.dataValues.admin = user.get('admin')
        }
        global.Response.success(ctx, undefined, replys)
    }

    /* ------------------------------------------------ok 删除回复 --------------------------------------------------------*/
    async deleteReply(ctx) {
        const {
            id
        } = ctx.query
        const res = await DB.reply.destroy({ // return 1 or 0
            where: {
                id
            }
        })

        if (res) {
            global.Response.success(ctx, '删除成功')
        } else {
            global.Response.null(ctx)
        }

    }


}

module.exports = new MsgController